package com.zt.chatgpt.openai.service.rule.impl;

import com.zt.chatgpt.openai.annotation.LogicStrategy;
import com.zt.chatgpt.openai.model.aggregates.ChatProcessAggregate;
import com.zt.chatgpt.openai.model.aggregates.UserAccountQuotaEntity;
import com.zt.chatgpt.openai.model.entity.RuleLogicEntity;
import com.zt.chatgpt.openai.model.valobj.LogicCheckTypeVO;
import com.zt.chatgpt.openai.repository.IOpenAiRepository;
import com.zt.chatgpt.openai.service.rule.ILogicFilter;
import com.zt.chatgpt.openai.service.rule.factory.DefaultLogicFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: zt
 * @Description: 用户模型额度扣减规则过滤
 * @create: 2024-05-22 20:30
 */
@Slf4j
@Component
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.USER_QUOTA)
public class UserQuotaFilter implements ILogicFilter<UserAccountQuotaEntity> {

    @Resource
    private IOpenAiRepository openAiRepository;

    @Override
    public RuleLogicEntity<ChatProcessAggregate> filter(ChatProcessAggregate chatProcessAggregate, UserAccountQuotaEntity data) throws Exception {
        // 1. 扣减用户额度,因为是个人账户无竞争，所以可用不用上锁
        if (data.getSurplusQuota() > 0) {
            int updateCount = openAiRepository.subAccountQuota(data.getOpenid());
            // 1.1 扣减成功
            if (0 != updateCount) {
                return RuleLogicEntity.<ChatProcessAggregate>builder()
                        .type(LogicCheckTypeVO.SUCCESS)
                        .info("用户额度扣减成功")
                        .data(chatProcessAggregate)
                        .build();
            }

            // 1.2 扣减失败
            return RuleLogicEntity.<ChatProcessAggregate>builder()
                    .type(LogicCheckTypeVO.REFUSE)
                    .info("个人账户，总额度【" + data.getTotalQuota() + "】次，已耗尽！")
                    .data(chatProcessAggregate)
                    .build();

        }

        // 2. 用户可用额度不足
        return RuleLogicEntity.<ChatProcessAggregate>builder()
                .type(LogicCheckTypeVO.REFUSE)
                .info("个人账户，总额度【" + data.getTotalQuota() + "】次，已耗尽！")
                .data(chatProcessAggregate)
                .build();
    }
}
